﻿using CSRedis;
using net8.Models;
using net8.Models.XiTong;

namespace net8.Helper
{
    /// <summary>
    /// CSRedisCore帮助类
    /// </summary>
    public static class CsRedisHelper
    {
        static CsRedisHelper()
        {
            string conn = AppConfig.Configuration["RedisConfig"];
            var client = new CSRedisClient(conn);
            RedisHelper.Initialization(client);
        }

        public static string Get(string key)
        {
            return RedisHelper.Get(key);
        }

        public static T Get<T>(string key) where T : new()
        {
            return RedisHelper.Get<T>(key);
        }

        public static async Task<string> GetAsync(string key)
        {
            return await RedisHelper.GetAsync(key);
        }

        public static async Task<T> GetAsync<T>(string key) where T : new()
        {
            return await RedisHelper.GetAsync<T>(key);
        }

        public static void Set(string key, object t, int expiresSec = 0)
        {
            RedisHelper.Set(key, t, expiresSec);
        }

        public static async Task SetAsync(string key, object t, int expiresSec = 0)
        {
            await RedisHelper.SetAsync(key, t, expiresSec);
        }

        public static void Init()
        {
            List<UserCache> userList = DbHelper.Db.Queryable<XtUser>()
                .Includes(u => u.RoleList, ur => ur.Role, rm => rm.PermissionList)
                .Select(u => new UserCache()
                {
                    UserId = u.Id,
                    IsEnable = u.IsEnable,
                    LoginId = u.LoginId,
                    RoleName = u.RoleList.Select(ur => ur.Role.RoleName).ToList(),
                    MenuList = u.RoleList.SelectMany(ur => ur.Role.PermissionList.Select(rm => rm.MenuId)).ToList()
                }).ToList();

            Set("UserCache", userList);

        }
    }
}
